<template>
  <div class="todo-app">
    <header class="todo-header">
      <h1>待办事项</h1>
      <el-input
        v-model="newTodo"
        placeholder="添加新待办..."
        @keyup.enter="addTodo"
        class="todo-input"
      >
        <template #append>
          <el-button @click="addTodo">
            <el-icon><Plus /></el-icon>
          </el-button>
        </template>
      </el-input>
    </header>
    
    <main class="todo-list-container">
      <div v-if="filteredTodos.length === 0" class="todo-empty">
        <el-empty description="暂无待办事项" />
      </div>
      <ul v-else class="todo-list">
        <li 
          v-for="todo in filteredTodos" 
          :key="todo.id" 
          class="todo-item"
          :class="{ 'completed': todo.completed }"
        >
          <el-checkbox v-model="todo.completed" />
          <div class="todo-content" @dblclick="startEditing(todo)">
            <template v-if="editingId !== todo.id">
              <span class="todo-text">{{ todo.text }}</span>
              <div class="todo-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  circle 
                  @click="startEditing(todo)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  circle 
                  @click="removeTodo(todo.id)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
            <template v-else>
              <el-input
                v-model="editText"
                @keyup.enter="finishEditing(todo.id)"
                @keyup.esc="cancelEditing"
                ref="editInput"
                size="small"
              />
              <div class="edit-actions">
                <el-button @click="finishEditing(todo.id)" size="small">保存</el-button>
                <el-button @click="cancelEditing" size="small">取消</el-button>
              </div>
            </template>
          </div>
        </li>
      </ul>
    </main>
    
    <footer class="todo-footer">
      <div class="todo-stats">
        <span>{{ activeTodosCount }} 项待办</span>
        <span>{{ completedTodosCount }} 项已完成</span>
      </div>
      <div class="todo-filters">
        <el-radio-group v-model="filter" size="small">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="active">未完成</el-radio-button>
          <el-radio-button label="completed">已完成</el-radio-button>
        </el-radio-group>
      </div>
      <div class="todo-actions">
        <el-button 
          v-if="completedTodosCount > 0" 
          @click="clearCompleted" 
          size="small" 
          type="danger"
        >
          清除已完成
        </el-button>
      </div>
    </footer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { v4 as uuidv4 } from 'uuid'

interface Todo {
  id: string
  text: string
  completed: boolean
  createdAt: Date
}

// 本地存储键
const STORAGE_KEY = 'todo-app-data'

// 待办列表
const todos = ref<Todo[]>([])

// 新待办输入
const newTodo = ref('')

// 编辑状态
const editingId = ref<string | null>(null)
const editText = ref('')
const editInput = ref<HTMLInputElement | null>(null)

// 过滤器
const filter = ref<'all' | 'active' | 'completed'>('all')

// 过滤后的待办列表
const filteredTodos = computed(() => {
  switch (filter.value) {
    case 'active':
      return todos.value.filter(todo => !todo.completed)
    case 'completed':
      return todos.value.filter(todo => todo.completed)
    default:
      return todos.value
  }
})

// 未完成待办数量
const activeTodosCount = computed(() => 
  todos.value.filter(todo => !todo.completed).length
)

// 已完成待办数量
const completedTodosCount = computed(() => 
  todos.value.filter(todo => todo.completed).length
)

// 添加新待办
const addTodo = () => {
  const text = newTodo.value.trim()
  if (text) {
    todos.value.push({
      id: uuidv4(),
      text,
      completed: false,
      createdAt: new Date()
    })
    newTodo.value = ''
    saveTodos()
  }
}

// 移除待办
const removeTodo = (id: string) => {
  todos.value = todos.value.filter(todo => todo.id !== id)
  saveTodos()
}

// 开始编辑待办
const startEditing = (todo: Todo) => {
  editingId.value = todo.id
  editText.value = todo.text
  nextTick(() => {
    editInput.value?.focus()
  })
}

// 完成编辑
const finishEditing = (id: string) => {
  const text = editText.value.trim()
  if (text) {
    const todo = todos.value.find(todo => todo.id === id)
    if (todo) {
      todo.text = text
      saveTodos()
    }
  } else {
    removeTodo(id)
  }
  cancelEditing()
}

// 取消编辑
const cancelEditing = () => {
  editingId.value = null
}

// 清除已完成待办
const clearCompleted = () => {
  todos.value = todos.value.filter(todo => !todo.completed)
  saveTodos()
}

// 保存待办到本地存储
const saveTodos = () => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(todos.value))
}

// 从本地存储加载待办
const loadTodos = () => {
  const savedTodos = localStorage.getItem(STORAGE_KEY)
  if (savedTodos) {
    try {
      todos.value = JSON.parse(savedTodos)
    } catch (e) {
      console.error('Failed to parse todos from localStorage', e)
      todos.value = []
    }
  }
}

// 初始化
onMounted(() => {
  loadTodos()
})
</script>

<style scoped>
.todo-app {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.todo-header {
  padding: 20px;
  background-color: #409eff;
  color: white;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

.todo-header h1 {
  margin: 0 0 16px;
  font-size: 24px;
}

.todo-input {
  width: 100%;
}

.todo-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.todo-empty {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.todo-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  transition: all 0.3s;
}

.todo-item:hover {
  background-color: #ecf5ff;
}

.todo-item.completed .todo-text {
  text-decoration: line-through;
  color: #909399;
}

.todo-content {
  flex: 1;
  margin-left: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.todo-text {
  font-size: 14px;
}

.todo-actions, .edit-actions {
  display: flex;
  gap: 5px;
}

.todo-footer {
  padding: 15px;
  background-color: #f5f7fa;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}

.todo-stats {
  display: flex;
  gap: 10px;
  color: #606266;
  font-size: 13px;
}

@media (max-width: 768px) {
  .todo-footer {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .todo-filters {
    align-self: center;
  }
}
</style> 